package com.example.test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        CountDownLatch countDownLatch = new CountDownLatch(5);

        for (int i = 0; i < 5; i++) {
            /**
             * index是每次循环“新声明”的变量，不是“一个变量多次赋值”！
             */
            final int index = i;
            executorService.execute(() -> {
                try {
                    System.out.println("任务" + index + "开始");
                    Thread.sleep(1000);
                    System.out.println("任务" + index + "结束");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        /**
         * 假设你是一个主线程，你要等待 3 个工人都完成了任务后，才开始下一步操作
         * 每个工人做完事情后调用 latch.countDown()；
         * 主线程在 latch.await() 上阻塞，直到 count == 0；
         * 当所有人都调用过一次 countDown() 后，主线程才能继续执行。
         */
        countDownLatch.await();
        System.out.println("全部完成");
        executorService.shutdown();

    }
}
